﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CommonMvc.Common;
using CommonMvc.Filters;
using CommonMvc.Middleware;
using CommonMvc.Models.CommonModels;
using CommonMvc.Models.Concreate;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Conditions;
using NLog.Config;
using NLog.Extensions.Logging;
using NLog.Targets;
using NLog.Web;

namespace CommonMvc
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var connection = AppSetting.GetConfig("ConnectionStrings:DataContext");
            services.AddDbContext<DataContext>(options =>
            options.UseSqlServer(connection));
            // .UseLazyLoadingProxies()

            //添加内存缓存
            services.AddMemoryCache();
            services.AddMvc(options =>
            {
                options.Filters.Add<ModelFilter>();
            });

            services.AddDistributedRedisCache(options =>
            {
                options.InstanceName = "ubuntu";
                options.Configuration = "47.98.111.73:6379,password=a123456A";
            });
            

            //注入httpContext
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            //注入cookie管理
            services.AddScoped<ICookieManager, CookieManager>();
            services.AddScoped<IAppContext, WebAppContext>();
            services.AddScoped<IWorkContext, WebWorkContext>();
         
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                //显示详细错误信息
                app.UseDeveloperExceptionPage();
                //显示ef core相关的错误信息
                app.UseDatabaseErrorPage();
                //显示错误页面
                app.UseStatusCodePagesWithRedirects("~/Home/about"); // 相对根路径
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
                routes.MapRoute(
                 name: "Sysmanager",
                 template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
               );
            });
            app.UseStaticFiles();
            app.UseMvc(routes =>
            {
               
            });
         
            loggerFactory.AddNLog();//添加NLog
            //env.ConfigureNLog("nlog.config");//读取Nlog配置文件
            SetNlogByCode();

            //服务器资源路径置换，这样可以防止客户端猜测服务端文件路径，制造一个虚拟的隐射进行访问，提高了安全性。
            app.UseStaticFiles(new StaticFileOptions()
             {
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot/Files")),
                RequestPath = new PathString("/src")
             });
            app.UseErrorHandling();
            app.UseRequestIP();//使用中间件
           
            //InitData(app.ApplicationServices);
        }
        #region 通过代码设置 nlog 日志相关规则
        public void SetNlogByCode() {
            // Step 1. Create configuration object 
           var config = new LoggingConfiguration();

            // Step 2. Create targets and add them to the configuration 
            var consoleTarget = new ColoredConsoleTarget();
            config.AddTarget("console", consoleTarget);    
            var fileTarget = new FileTarget();
            config.AddTarget("file", fileTarget);

            //Step 3. Set target properties
            ConsoleRowHighlightingRule consoleRowHighlightingRule = new ConsoleRowHighlightingRule()
             {
                 BackgroundColor = ConsoleOutputColor.White,
                 ForegroundColor = ConsoleOutputColor.DarkBlue,
                  Condition  =  ConditionParser.ParseExpression("level == LogLevel.Info")
             };
            consoleTarget.RowHighlightingRules.Add(consoleRowHighlightingRule);
            consoleTarget.Layout = @"${date:format=HH\:mm\:ss} ${logger} ${message}";
            fileTarget.FileName = "${basedir}/Logs/Default/${uppercase:${level}}/${shortdate}.log";
            fileTarget.Layout = "${longdate} ${message}";
            fileTarget.CreateDirs = true;
            fileTarget.Encoding = Encoding.UTF8;

            // Step 4. Define rules
            var rule1 = new LoggingRule("*", NLog.LogLevel.Debug, consoleTarget);
            config.LoggingRules.Add(rule1);

            var rule2 = new LoggingRule("file", NLog.LogLevel.Debug, fileTarget);
            config.LoggingRules.Add(rule2);

            // Step 5. Activate the configuration
            LogManager.Configuration = config;
        }
        #endregion
        /// <summary>
        /// 根据条件 给数据库初始化一些数据
        /// </summary>
        /// <param name="serviceProvider"></param>
        public void InitData(IServiceProvider serviceProvider) {
            using (var serviceScope =
                serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope()) {
                var db = serviceScope.ServiceProvider.GetService<DataContext>();
                db.Database.EnsureCreated();//
                if (db.RolePermissions.Count() == 0) {
                    var rolePermissionsList = new List<RolePermission>
                    {
                        new RolePermission(){
                            RoleId = 1,
                            Controller = "Person",
                            Action = "Index"
                        }
                    };
                    db.RolePermissions.AddRange(rolePermissionsList);
                    db.SaveChanges();
                }


            }
        }

    }


}
